package fr.alesia.deepstack.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.Ranking;
import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.factory.DaoFactory;
import fr.alesia.deepstack.io.BeanWriter;
import fr.alesia.deepstack.io.impl.PlayerWriter;
import fr.alesia.deepstack.io.impl.RankingWriter;
import fr.alesia.deepstack.io.impl.TournamentWriter;

@SuppressWarnings("serial")
public class ExportServlet extends HttpServlet {
	
	@Override
	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		ServletContext context = this.getServletContext();

		String type = request.getParameter("type");
		if(type == null || type.trim().length() == 0){
			
		}
		else{
			
			try{
				response.setContentType("application/x-download");
				OutputStream stream = response.getOutputStream( );
				
				if(type.equals("player")){
					
					response.setHeader("Content-Disposition", "attachment;filename=players.csv");
					Set<Player> players = DaoFactory.getPlayerDao().findAll();
					BeanWriter<Player> writer = PlayerWriter.getInstance();
					writer.write(stream, players);
				}
				if(type.equals("tournament")){
					
					response.setHeader("Content-Disposition", "attachment;filename=tournaments.csv");
					Set<Tournament> tournaments = DaoFactory.getTournamentDao().findAll();
					BeanWriter<Tournament> writer = TournamentWriter.getInstance();
					writer.write(stream, tournaments);
				}
				if(type.equals("ranking")){
				
					response.setHeader("Content-Disposition", "attachment;filename=rankings.csv");
					Set<Ranking> rankings = DaoFactory.getRankingDao().findAll();
					BeanWriter<Ranking> writer = RankingWriter.getInstance();
					writer.write(stream, rankings);
				}
				if(type.equals("database")){
					
					response.setHeader("Content-Disposition", "attachment;filename=database.zip");
				}
			}
			catch(Exception e){			
				e.printStackTrace();
			}
		}
		
		RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/admin/export.jsp");
		dispatcher.forward(request, response);
	}

	@Override
	protected void doPost (
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		this.doGet(request, response);
	}
}
